package com.hk.redundantcode.templatemethod;

import com.hk.redundantcode.templatemethod.right.AbstractCart;
import com.hk.redundantcode.templatemethod.wrong.InternalUserCart;
import com.hk.redundantcode.templatemethod.wrong.NormalUserCart;
import com.hk.redundantcode.templatemethod.wrong.VipUserCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: dpb
 * @Description TODO
 * @date: 2023/2/1 23:32
 * @Version 1.0
 */
@RestController
@RequestMapping("templateMethod")
public class TemplateMethodController {

    private static Map<Long, Integer> items = new HashMap<>();

    @Autowired
    private ApplicationContext applicationContext;

    static {
        items.put(1L, 2);
        items.put(2L, 4);
    }


    @GetMapping("wrong")
    public Cart wrong(@RequestParam("userId") int userId) {
        String userCategory = Db.getUserCategory(userId);
        switch (userCategory) {
            case "normal":
                NormalUserCart normalUserCart = new NormalUserCart();
                return normalUserCart.process(userId, items);
            case "vip":
                VipUserCart vipUserCart = new VipUserCart();
                return vipUserCart.process(userId,items);
            case "internal":
                InternalUserCart internalUserCart = new InternalUserCart();
                return internalUserCart.process(userId,items);
        }
        return null;
    }

    /**
     * 使用工厂+模板设计模式简化了冗余代码并提高了扩展性，去掉了if..else，更加的优雅
     * @param userId
     * @return
     */
    @GetMapping("right")
    public Cart right(@RequestParam("userId") int userId) {
        String userCategory = Db.getUserCategory(userId);
        userCategory = userCategory + "UserCart";
        Map<String, AbstractCart> beansOfType = applicationContext.getBeansOfType(AbstractCart.class);
        if (null != beansOfType.get(userCategory)) {
            AbstractCart abstractCart = beansOfType.get(userCategory);
            return abstractCart.process(userId, items);
        }
        return null;
    }


}
